package io.github.wslxm.springbootplus2.manage.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.github.wslxm.springbootplus2.client.sys.model.vo.USysDictGroupVO;
import io.github.wslxm.springbootplus2.client.sys.model.vo.USysDictVO;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.core.config.error.ErrorException;
import io.github.wslxm.springbootplus2.core.enums.BaseDic;
import io.github.wslxm.springbootplus2.core.result.ResultType;
import io.github.wslxm.springbootplus2.core.utils.XjBeanUtil;
import io.github.wslxm.springbootplus2.core.utils.XjStringUtil;
import io.github.wslxm.springbootplus2.core.utils.tree.XjTreeUtil;
import io.github.wslxm.springbootplus2.core.utils.validated.XjValidUtil;
import io.github.wslxm.springbootplus2.manage.sys.dao.SysDictDao;
import io.github.wslxm.springbootplus2.manage.sys.mapper.SysDictMapper;
import io.github.wslxm.springbootplus2.manage.sys.model.dto.SysDictDTO;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysDict;
import io.github.wslxm.springbootplus2.manage.sys.model.query.SysDictQuery;
import io.github.wslxm.springbootplus2.manage.sys.model.vo.SysDictVO;
import io.github.wslxm.springbootplus2.manage.sys.service.SysDictService;
import io.github.wslxm.springbootplus2.manage.sys.handle.SysDictServiceHandle;
import io.github.wslxm.springbootplus2.starter.redis.lock.XjDistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author wangsong
 */
@Service
@Slf4j
public class SysDictServiceImpl extends BaseServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Autowired
    private SysDictDao sysDictDao;
    @Autowired
    private SysDictServiceHandle sysDictServiceHandle;

    /**
     * 父级pid
     */
    private static final String PID = "0";

    @Override
    public List<SysDictVO> tree(SysDictQuery query) {
        // 1、判断 code, 不能传递字符串数字来查询
        if (StringUtils.isNotBlank(query.getCode())) {
            XjValidUtil.isTrue(XjStringUtil.isInteger(query.getCode()), "sys.config.code.NotInt");
        }
        String code = query.getCode();
        List<SysDictVO> dictListVO = null;
        // 处理查询参数
        boolean isDisable = ObjectUtil.defaultIfNull(query.getIsDisable(), true);
        if (StringUtils.isNotBlank(code)) {
            // code 查询
            SysDict dictionary = this.getOne(new LambdaQueryWrapper<SysDict>().select(SysDict::getId)
                    .eq(SysDict::getCode, code)
            );
            XjValidUtil.isTrue(dictionary == null, ResultType.BASE_NO_RESP_DATA);
            List<SysDict> dictList = this.list(new LambdaQueryWrapper<SysDict>()
                    .orderByAsc(SysDict::getSort)
                    .orderByDesc(SysDict::getCreateTime)
                    .eq(SysDict::getPid, dictionary.getId())
                    .eq(!isDisable, SysDict::getDisable, BaseDic.Whether.V0.getValue())
            );
            dictListVO = XjBeanUtil.listVo(dictList, SysDictVO.class);
        } else {
            // tree 查询
            List<SysDict> dictList = this.list(new LambdaQueryWrapper<SysDict>()
                    .orderByAsc(SysDict::getSort)
                    .orderByDesc(SysDict::getCreateTime)
                    .in(SysDict::getType, BaseDic.DictType.V1.getValue(), BaseDic.DictType.V2.getValue())
                    .eq(!isDisable, SysDict::getDisable, BaseDic.Whether.V0.getValue())
            );
            List<SysDictVO> dictionaryVos = XjBeanUtil.listVo(dictList, SysDictVO.class);
            SysDictVO dictionaryVO = XjTreeUtil.nextTree(dictionaryVos, PID);
            dictListVO = dictionaryVO.getChildren();
        }
        return dictListVO;
    }


    @Override
    @XjDistributedLock(lockName = "'xj-sys-dict_'+#dto.code", waitTime = 5L)
    public String insert(SysDictDTO dto) {
        String code = dto.getCode().trim();
        if (StringUtils.isBlank(code)) {
            throw new ErrorException("sys.dict.code.NotBlank");
        }
        // 字典: code 不能重复
        // 字典值: 字典值在在同一个 pid 下 code 不能重复, 但 A字典与B字典下的 code 可以重复
        this.verifyCodeRepeat(dto.getType(), dto.getPid(), code, null);
        // 数据结构验证(防止误添加)
        this.verifyDictLevel(dto);

        // 添加
        SysDict entity = dto.convert(SysDict.class);
        dto.setCode(code);
        boolean b = this.save(entity);
        return entity.getId();
    }


    @Override
    @XjDistributedLock(lockName = "'xj-sys-dict_'+#dto.code", waitTime = 5L)
    public Boolean upd(String id, SysDictDTO dto) {
        // 因为code不能重复, 编辑了code 需单独处理数据
        if (dto.getCode() != null) {
            // 在同一个pid 下code不能重复
            String code = dto.getCode().trim();
            dto.setCode(code);
            this.verifyCodeRepeat(dto.getType(), dto.getPid(), code, id);
        }
        // 数据结构验证(防止误添加)
        this.verifyDictLevel(dto);
        //
        SysDict entity = dto.convert(SysDict.class);
        entity.setId(id);
        return this.updateById(entity);
    }

    @Override
    public Boolean del(String id) {
        List<SysDict> list = this.list();
        List<SysDictVO> dictionaryVOS = XjBeanUtil.listVo(list, SysDictVO.class);
        List<String> ids = XjTreeUtil.getNextIds(dictionaryVOS, id);
        ids.add(id);
        return this.removeByIds(ids);
    }

    @Override
    public Map<String, List<USysDictGroupVO>> findCodeGroup() {
        List<SysDict> list = this.list(new LambdaQueryWrapper<SysDict>()
                .orderByAsc(SysDict::getSort)
                .orderByDesc(SysDict::getCreateTime)
        );
        Map<String, List<SysDict>> dictByPidMap = list.stream().collect(Collectors.groupingBy(SysDict::getPid));
        List<SysDict> dictList = list.stream().filter(p -> p.getType().equals(BaseDic.DictType.V2.getValue())).collect(Collectors.toList());
        Map<String, List<USysDictGroupVO>> dictMap = new HashMap<>();
        for (SysDict dict : dictList) {
            List<SysDict> dictionaries = dictByPidMap.get(dict.getId());
            List<USysDictGroupVO> dictionaryCodeGroupVos = XjBeanUtil.listVo(dictionaries, USysDictGroupVO.class);
            dictMap.put(dict.getCode(), dictionaryCodeGroupVos);
        }
        return dictMap;
    }

    @Override
    public List<USysDictVO> findByCode(String code) {
        return sysDictDao.findByCode(code);
    }

    @Override
    public Map<String, USysDictVO> findMapByCode(String code) {
        return sysDictDao.findMapByCode(code);
    }

    @Override
    public USysDictVO findByCodeNext(String code, String nextCode) {
        return sysDictDao.findByCodeNext(code, nextCode);
    }


    @Override
    public Map<String, String> generateEnum(String pid) {
       return sysDictServiceHandle.generateEnum(pid);
    }


    /**
     * 字典code重复验证
     *
     * @author wangsong
     * @mail 1720696548@qq.com
     * @date 2022/8/20 0020 14:33 验证
     * @version 1.0.0
     */
    private void verifyCodeRepeat(Integer type, String pid, String code, String excludeId) {
        if (type.equals(BaseDic.DictType.V3.getValue())) {
            long count = this.count(new LambdaQueryWrapper<SysDict>()
                    .and(p -> p.eq(SysDict::getPid, pid).eq(SysDict::getCode, code).ne(excludeId != null, SysDict::getId, excludeId))
                    .or(p -> p.ne(SysDict::getType, BaseDic.DictType.V3.getValue()).eq(SysDict::getCode, code).ne(excludeId != null, SysDict::getId, excludeId))
            );
            XjValidUtil.isTrue(count > 0, ResultType.BASE_CODE_REPEAT);
        } else {
            long count = this.count(new LambdaQueryWrapper<SysDict>()
                    .eq(SysDict::getCode, code)
                    .ne(excludeId != null, SysDict::getId, excludeId)
            );
            XjValidUtil.isTrue(count > 0, ResultType.BASE_CODE_REPEAT);
        }
    }

    /**
     * 层级验证
     * 添加目录pid 必须为0
     * 添加字典 pid 的数据必须是目录
     * 添加字典值 pid 的数据必须是字典
     *
     * @param dto
     */
    private void verifyDictLevel(SysDictDTO dto) {
        if (dto.getType().equals(BaseDic.DictType.V1.getValue())) {
            XjValidUtil.isTrue(!dto.getPid().equals("0"), "sys.dict.type.Level");
        } else if (dto.getType().equals(BaseDic.DictType.V2.getValue())) {
            SysDict parentDict = this.getById(dto.getPid());
            XjValidUtil.isTrue(!parentDict.getType().equals(BaseDic.DictType.V1.getValue()), "sys.dict.type.Level");
        } else if (dto.getType().equals(BaseDic.DictType.V3.getValue())) {
            SysDict parentDict = this.getById(dto.getPid());
            XjValidUtil.isTrue(!parentDict.getType().equals(BaseDic.DictType.V2.getValue()), "sys.dict.type.Level");
        }
    }
}

